package com.onlineMIS.action.headQ.finance;


import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.onlineMIS.ORM.DAO.JspLoadResult;
import com.onlineMIS.ORM.DAO.Response;
import com.onlineMIS.ORM.DAO.chainS.ChainUtility;
import com.onlineMIS.ORM.DAO.headQ.finance.FinanceService;
import com.onlineMIS.ORM.DAO.headQ.user.UserInforDaoImpl;
import com.onlineMIS.ORM.DAO.headQ.user.UserInforService;
import com.onlineMIS.ORM.entity.base.BaseOrder;
import com.onlineMIS.ORM.entity.chainS.user.ChainUserInfor;
import com.onlineMIS.ORM.entity.headQ.finance.ExpenseHq;
import com.onlineMIS.ORM.entity.headQ.custMgmt.HeadQCust;
import com.onlineMIS.ORM.entity.headQ.finance.FinanceBill;
import com.onlineMIS.ORM.entity.headQ.finance.FinanceBillCorpFlow;
import com.onlineMIS.ORM.entity.headQ.finance.FinanceBillFlowDetailsVO;
import com.onlineMIS.ORM.entity.headQ.finance.FinanceBillItem;

import com.onlineMIS.ORM.entity.headQ.finance.FinanceBillVO;

import com.onlineMIS.ORM.entity.headQ.finance.FinanceCategory;
import com.onlineMIS.ORM.entity.headQ.supplier.purchase.PurchaseOrder;
import com.onlineMIS.ORM.entity.headQ.supplier.supplierMgmt.HeadQSupplier;

import com.onlineMIS.ORM.entity.headQ.user.UserInfor;
import com.onlineMIS.common.Common_util;
import com.onlineMIS.common.loggerLocal;
import com.opensymphony.xwork2.ActionContext;import javassist.expr.NewArray;

@Controller
public class FinanceJSPAction extends FinanceAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1120066931973798941L;
	private final String templateFinaceBillHQ = "FinanceBillHQ.xls";
	private final String templateAcctFlowHQ = "AcctFlowHQ.xls";
	private final String templateExpenseHqDetails = "ExpenseHqItemDetails.xls";
	private final String templateAcctFlowDetailsHQ = "HeadCustAccountsDealings.xls";
	private String excelFileName = "";
	private InputStream excelStream;
	@Autowired
	private FinanceService financeService;
	@Autowired
	private UserInforService userInforService;
	//账目流水详情模版
	private final String templateAccountsFlow = "AccountFlowHQTemplate.xls";
	
	//所有账目流水
	private final String templateAllAccountsFlow = "AllAccountFlowHQTemplate.xls";
	
	//精算模板
	private final String templateAllAccountsJSFlow = "AllAccountJSFlowHQTemplate.xls";
	
	//账目详情模版
	private final String templateFinanceCategory = "FinanceCategoryTemplate.xls";
	

	public void setExcelStream(InputStream excelStream) {
		this.excelStream = excelStream;
	}
	
	public String getExcelFileName() {
		return excelFileName;
	}

	public InputStream getExcelStream() {
		return excelStream;
	}

	public void setExcelFileName(String excelFileName) {
		this.excelFileName = Common_util.encodeAttachment(excelFileName);
	}
	

	
	/**
	 * 创建客户财务单据
	 * @return
	 */
	public String preCreateFHQ(){
		loggerLocal.info("FinanceJSPAction.preCreateFHQ ");
		Response response = financeService.prepareCreateBill(formBean, uiBean);		
		ChainUtility.calculateParam(formBean, new FinanceBill());
		if (!response.isSuccess()) {
			ActionContext.getContext().getSession().put(JspLoadResult.LOAD_RESULT, new JspLoadResult(JspLoadResult.LOAD_RESULT_FAIL, response.getMessage()));
		}
		
		return "EditFinanceBill";
	}
	
	
	/**
	 * 查看客户财务账号流水详情
	 * 
	 * @return
	 */
	public String cardFlowDetails() {
		UserInfor loginUserInfor = (UserInfor) ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		int cardId = formBean.getFc().getId();
		loggerLocal.info(loginUserInfor.getUser_name() + " : FinanceJSPAction.cardFlowDetails , " + cardId);
		financeService.insertCategory(formBean,cardId);

		return "flowDetails";
	}
	
	/**
	 * 下载账目信息报表
	 * @return
	 */																					
	public String downloadFinanceCategory() {
		loggerLocal.info(this.getClass().getName() + ".downloadFinanceCategory");
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
				.get(ServletActionContext.HTTP_REQUEST);
		String contextPath = request.getRealPath("/");
		Response response = new Response();
		try {
			response = financeService.generateFinanceCategoryExcel(
					contextPath + "WEB-INF\\template\\" + templateFinanceCategory,formBean);
		} catch (Exception e) {
			response.setReturnCode(Response.FAIL);
			response.setMessage(e.getMessage());
		}

		if (response.getReturnCode() == Response.SUCCESS) {
			InputStream excelStream = (InputStream) response.getReturnValue();
			formBean.setFileStream(excelStream); 
			formBean.setFileName(templateFinanceCategory);
			return "download";						
		} else
			return ERROR;
	}
	
	
	/**
	 * 下载账目信息报表 - 多选账目流水(精算格式）
	 * @return
	 */																					
	public String downloadFcFlow() {
		loggerLocal.info(this.getClass().getName() + ".downloadFcFlow");
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
				.get(ServletActionContext.HTTP_REQUEST);
		String contextPath = request.getRealPath("/");
		Response response = new Response();
		try {
			response = financeService.generateFcFlowExcel(
					contextPath + "WEB-INF\\template\\" + templateAllAccountsJSFlow,formBean);
		} catch (Exception e) {
			response.setReturnCode(Response.FAIL);
			response.setMessage(e.getMessage());
		}

		if (response.getReturnCode() == Response.SUCCESS) {
			InputStream excelStream = (InputStream) response.getReturnValue();
			formBean.setFileStream(excelStream); 
			formBean.setFileName(templateAccountsFlow);
			return "download";						
		} else
			return ERROR;
	}
	
	/**
	 * 下载账目信息报表 - 多选账目流水
	 * @return
	 */																					
	public String downloadFcAllFlow() {
		loggerLocal.info(this.getClass().getName() + ".downloadFcFlow");
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
				.get(ServletActionContext.HTTP_REQUEST);
		String contextPath = request.getRealPath("/");
		Response response = new Response();
		try {			
			response = financeService.generateFcAllFlowExcel(
					contextPath + "WEB-INF\\template\\" + templateAllAccountsFlow,formBean);
		} catch (Exception e) {
			response.setReturnCode(Response.FAIL);
			response.setMessage(e.getMessage());
		}

		if (response.getReturnCode() == Response.SUCCESS) {
			InputStream excelStream = (InputStream) response.getReturnValue();
			formBean.setFileStream(excelStream); 
			formBean.setFileName(templateAccountsFlow);
			return "download";						
		} else
			return ERROR;
	}
	
	
	/**
	 * 下载账目流水报表
	 * @return
	 */																					
	public String downloadAccountsFlow() {
		loggerLocal.info(this.getClass().getName() + ".downloadAccountsFlow");
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
				.get(ServletActionContext.HTTP_REQUEST);
		String contextPath = request.getRealPath("/");
		Response response = new Response();
		try {
			response = financeService.generateAcctFlowHQExcel(
					contextPath + "WEB-INF\\template\\" + templateAccountsFlow, formBean);
		} catch (Exception e) {
			response.setReturnCode(Response.FAIL);
			response.setMessage(e.getMessage());
		}

		if (response.getReturnCode() == Response.SUCCESS) {
			InputStream excelStream = (InputStream) response.getReturnValue();
			formBean.setFileStream(excelStream); 
			formBean.setFileName(templateAccountsFlow);
			return "download";						
		} else
			return ERROR;
	}
	
	
	/**
	 * 进入账目流水下载条件选择页面
	 * @return
	 */
	public String preFincaceFlowDownload(){
		loggerLocal.info("FinanceJSPAction.preFincaceFlowDownload");
		
		financeService.insertFinanceCategorys(formBean,uiBean);
		
		return "downloadFinanceFlow";
	}
	

	
	/**
	 * 删除单据
	 * @return
	 */
	public String deleteFHQBill(){
		loggerLocal.info("FinanceJSPAction.deleteFHQBill");
		
		UserInfor loginUserInfor = (UserInfor)ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		FinanceBill financeBill = formBean.getFinanceBill();
		
		if (financeBill.getId() != 0){
		    formBean.getFinanceBill().setCreatorHq(loginUserInfor);
		
		    financeService.deleteFHQBill(formBean.getFinanceBill());
		}
		
		formBean.initialize();
		
		addActionMessage("成功删除单据");
		return preCreateFHQ();	
	}
	
	/**
	 * 红冲单据
	 * @return
	 * @throws ParseException 
	 */
	public String cancelFHQBill() throws ParseException{
		loggerLocal.info("FinanceJSPAction.cancelFHQBill");
		
		UserInfor loginUserInfor = (UserInfor)ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		FinanceBill financeBill = formBean.getFinanceBill();
		
		if (financeBill.getId() != 0){
		    formBean.getFinanceBill().setCreatorHq(loginUserInfor);
		
		    Response response = financeService.cancelFHQBill(formBean.getFinanceBill());
		    if (response.getReturnCode() != Response.SUCCESS){
		    	addActionError(response.getMessage());
				
				formBean.initialize();
				return preCreateFHQ();	
		    }
		}

		formBean.initialize();
		addActionMessage("成功红冲单据");
		return preCreateFHQ();	
	}
	
	/**
	 * to redirect to the head q search page
	 * @return
	 */
	public String preSearchFHQ(){
		financeService.prepareCreateBill(formBean, uiBean);

		return "preSearchFinanceBill";
	}

	
	/**
	 * to get the finance bill from the head quarter part
	 * @return
	 */
	public String getFHQ(){
		String destination = "";
		
		FinanceBill financeBill = financeService.getFinanceBillById(formBean.getFinanceBill().getId());
		
		int status = financeBill.getStatus();
		formBean.setHeadQCust(financeBill.getCust());
		switch (status) {
		    case FinanceBill.STATUS_DRAFT: 
		    	
		    	formBean.setFinanceBill(financeBill); 
		    	financeService.prepareEditBill(formBean, financeBill.getChainStore());
		    	destination = "EditFinanceBill"; break;
		    case FinanceBill.STATUS_COMPLETE: 
		    case FinanceBill.STATUS_CANCEL:
		    	uiBean.setFinanceBill(financeBill); 
		    	destination = "ViewFinanceBill"; break;
		    default: destination = "error"; break;
		}
		
		ChainUtility.calculateParam(formBean, financeBill);
		
		return destination;
	}
	
	/**
	 * the user click the Edit bill button to try to edit the bill
	 * @return
	 */
	public String editFHQBill(){
		FinanceBill financeBill = financeService.getFinanceBillById(formBean.getFinanceBill().getId());
		
		formBean.setFinanceBill(financeBill); 
		financeService.prepareEditBill(formBean, financeBill.getChainStore());
		
		ChainUtility.calculateParam(formBean, financeBill);
		
		return "EditFinanceBill";
	}
	
	/**
	 * 搜索帐户流
	 * @return
	 */
	public String preSearchAcctFlow(){
    	UserInfor userInfor = (UserInfor)ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
    	loggerLocal.info(userInfor.getUser_name() + "," + this.getClass().getName() + "." + "preSearchAcctFlow");

		return "preSearchAcctFlow";
	}
	
	/**
	 * 搜索帐户流
	 * @return
	 */
	public String preFinanceRpt(){
    	UserInfor userInfor = (UserInfor)ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
    	loggerLocal.info(userInfor.getUser_name() + "," + this.getClass().getName() + "." + "preFinanceRpt");
    	
		financeService.prepareSearchAcctFlowUI(uiBean,formBean, userInfor);

		return "preFinanceRpt";
	}	
	
	/**
	 * 客户财务管理 - 查询客户预存金单据
	 * @return
	 */
	public String preFinancePrestore(){
    	UserInfor userInfor = (UserInfor)ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
    	loggerLocal.info(userInfor.getUser_name() + "," + this.getClass().getName() + "." + "preFinancePrestore");
    	
		financeService.prepareSearchAcctFlowUI(uiBean,formBean, userInfor);

		return "preFinanceInfo";
	}	

	
	/**
	 * 下载 批发财务单据
	 * @return
	 */																					
	public String downloadFHQBill() {
		loggerLocal.info(this.getClass().getName() + ".downloadFHQBill");
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
				.get(ServletActionContext.HTTP_REQUEST);
		String contextPath = request.getRealPath("/");
		Response response = new Response();
		try {
			response = financeService.generateFinanceBillHQRptExcel(
					contextPath + "WEB-INF\\template\\" + templateFinaceBillHQ, formBean);
		} catch (Exception e) {
			response.setReturnCode(Response.FAIL);
			response.setMessage(e.getMessage());
		}

		if (response.getReturnCode() == Response.SUCCESS) {
			InputStream excelStream = (InputStream) response.getReturnValue();
			formBean.setFileStream(excelStream); 
			formBean.setFileName(templateFinaceBillHQ);
			return "download";
			
			
		} else
			return ERROR;
	}

	
	/**
	 * 进入财务账目种类 列表
	 * @return
	 */
	public String preFinanceCategory() {
    	UserInfor userInfor = (UserInfor)ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
    	loggerLocal.info(userInfor.getUser_name() + "," + this.getClass().getName() + "." + "preFinanceCategory");
    	
		financeService.prepareSearchAcctFlowUI(uiBean,formBean, userInfor);
		
		return "preFinanceCategory";
	}
	
	

	
	
	/**
	 * 下载 客户往来账单据
	 * @return
	 */																					
	public String downloadAcctFlow() {
		loggerLocal.info(this.getClass().getName() + ".downloadAcctFlow");
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
				.get(ServletActionContext.HTTP_REQUEST);
		String contextPath = request.getRealPath("/");
		Response response = new Response();
		try {
			response = financeService.generateAcctFlowExcel(
					contextPath + "WEB-INF\\template\\" + templateAcctFlowHQ, formBean);
		} catch (Exception e) {
			response.setReturnCode(Response.FAIL);
			response.setMessage(e.getMessage());
		}

		if (response.getReturnCode() == Response.SUCCESS) {
			InputStream excelStream = (InputStream) response.getReturnValue();
			formBean.setFileStream(excelStream); 
			formBean.setFileName(templateAcctFlowHQ);
			return "download";
		} else
			return ERROR;
	}
	
	
	/**
	 * 下载 客户往来账单据
	 * @return
	 */																					
	public String downloadAcctFlowDetails() {
		loggerLocal.info(this.getClass().getName() + ".downloadAcctFlow");
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
				.get(ServletActionContext.HTTP_REQUEST);
		String contextPath = request.getRealPath("/");
		Response response = new Response();
		try {
			response = financeService.generateAcctFlowDetailsExcel(
					contextPath + "WEB-INF\\template\\" + templateAcctFlowDetailsHQ, formBean);
		} catch (Exception e) {
			response.setReturnCode(Response.FAIL);
			response.setMessage(e.getMessage());
		}

		if (response.getReturnCode() == Response.SUCCESS) {
			InputStream excelStream = (InputStream) response.getReturnValue();
			formBean.setFileStream(excelStream); 
			formBean.setFileName("AcctFlowHqDetails.xls");
			return "download";
		} else
			return ERROR;
	}

	
	/**
	 * 下载总部费用单据明细
	 * @return
	 */																					
	public String downloadExpenseHqDetails() {
		loggerLocal.info(this.getClass().getName() + ".downloadExpenseHqDetails");
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		String contextPath = request.getRealPath("/");
		Response response = new Response();
		try {
			response = financeService.generateExpenseHqDetailsExcel(
					contextPath + "WEB-INF\\template\\" + templateExpenseHqDetails, formBean);
		} catch (Exception e) {
			response.setReturnCode(Response.FAIL);
			response.setMessage(e.getMessage());
		}

		if (response.getReturnCode() == Response.SUCCESS) {
			InputStream excelStream = (InputStream) response.getReturnValue();
			formBean.setFileStream(excelStream); 
			formBean.setFileName(templateExpenseHqDetails);
			return "download";
		} else
			return ERROR;
	}

	
	/**
	 * 新增或者更新一个账目
	 * @return
	 */
	public String editFinanceCategory() {
		Response response = financeService.editFinanceCategory(formBean.getFc());
		if (response.isSuccess()){
			Object dataObj = response.getReturnValue();
			if (dataObj != null) {
				List data = (List)dataObj;
				FinanceCategory fc = (FinanceCategory) data.get(0);
				Double accuAmt = (Double) data.get(1) + fc.getInitialAmt();
				formBean.setFc(fc);
				formBean.getFcVo().setAcumulateAmt(Common_util.getFormatDouble(accuAmt));
			}
		} else 
			addActionError(response.getMessage());
		
		return "editFinanceCategory";
	}
	
	/**
	 * 进入财务账目种类 列表
	 * @return
	 */
	public String preFinanceBillCorpFlow() {
    	UserInfor userInfor = (UserInfor)ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
    	loggerLocal.info(userInfor.getUser_name() + "," + this.getClass().getName() + "." + "preFinanceBillCorpFlow");
    	
    	List<FinanceCategory> list = financeService.selectIsTransferAccountsFc();
    	uiBean.setFinanceCategory(list);
    	List<UserInfor> userInfors = userInforService.selectAccounting();
    	uiBean.setUserInfors(userInfors);
		
		return "preFinanceBillCorpFlow";
	}
	
	
	/**
	 * 进入总部费用创建/修改草稿页面, 详情页面
	 * load Expense
	 * @return
	 */
	public String editExpense() {
    	UserInfor userInfor = (UserInfor)ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
    	loggerLocal.info(userInfor.getUser_name() + "," + this.getClass().getName() + "." + "editExpense");
    	
    	Response response = financeService.loadExpense(formBean.getExpenseHq());
		if (!response.isSuccess()){
			addActionError(response.getMessage());
			return "error";
		}		
		
		String destination = "";

		ExpenseHq expenseHq = (ExpenseHq)response.getReturnValue();
		formBean.setExpenseHq(expenseHq);
		
		int status = expenseHq.getStatus();
		switch (status) {
		   case ExpenseHq.STATUS_INITIAL:
			   
	       case ExpenseHq.STATUS_DRAFT: 
	    	
	    	   financeService.prepareEditExpense(formBean, uiBean);
	    	   destination = "editExpense"; break;
	        case ExpenseHq.STATUS_COMPLETE: 
	        case ExpenseHq.STATUS_CANCEL:
	    	
	    	destination = "expenseDetails"; break;
	        default: destination = "error"; break;
	    }
		
		ChainUtility.calculateParam(formBean, formBean.getExpenseHq());

		return destination;
	}
	
	
	/**
	 * 进步总部费用明细页面
	 * @return
	 */
	public String editExpenseInfo() {
    	UserInfor userInfor = (UserInfor)ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
    	loggerLocal.info(userInfor.getUser_name() + "," + this.getClass().getName() + "." + "editExpenseInfo");
    	
    	List<FinanceCategory> list = financeService.selectIsTransferAccountsFc();
    	uiBean.setFinanceCategory(list);
    			
		return "editExpenseInfo";
	}
	

	
	/**
	 * 调取 一个FinanceBillCorp Flow
	 * @return
	 */
	public String editFinanceBillCorpFlow() {
		
		Response response = financeService.editFinanceBillCorpFlow(formBean, uiBean,formBean.getFinanceBillCorpFlow());

		if (!response.isSuccess()){

			addActionError(response.getMessage());
		}
		
		return "editFinanceBillCorpFlow";
	}
	
	/**
	 * 查询机构转账账目信息
	 * @return
	 *
	public String updateFinanceBillCorpFlow() {
		
		List<FinanceCategory> list = financeService.selectFinanceCategoryAll();
		
		uiBean.setFinanceCategory(list);
		FinanceBillCorpFlow flow = financeService.selectFCorpFlowById(formBean.getFinanceBillCorpFlow().getId());
		if (flow != null) {
			uiBean.setFinanceBillCorpFlow(flow);
		}
	
		formBean.setFinanceBillCorpFlow(flow);
		
		return "updateFinanceBillCorpFlow";
	}*/

}
